package org.bing.engine.common.graniteds;

import java.util.HashMap;
import java.util.Map;

public class SimpleBeanFactory {
    private static final Map<String, Object> map = new HashMap<String, Object>();

    @SuppressWarnings("unchecked")
    public static synchronized <T> T findService(Class<T> clz) {
        String clzName = clz.getName();
        Object obj = map.get(clzName);
        if (obj == null) {
            try {
                obj = clz.newInstance();
                map.put(clzName, obj);
            } catch (Exception e) {
                throw new RuntimeException("Fail to instance " + clzName, e);
            }
        }
        return (T) obj;
    }

    public static synchronized Object findService(String clzName) {
        try {
            return findService(Class.forName(clzName));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException("Class not found - " + clzName, e);
        }
    }
}
